package com.yu.mall.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yu.mall.dto.PageDTO;
import com.yu.mall.entity.White;
import com.yu.mall.service.WhiteService;
import com.yu.mall.util.ResultUtils;
import com.yu.mall.vo.PageResultVO;
import com.yu.mall.vo.ResultVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("white")
@Api(tags = "白名单管理",value = "白名单管理")
public class WhiteController {

    @Autowired
    WhiteService whiteService;

    @PostMapping("add")
    @ApiOperation(value = "添加白名单")
    public ResultVO add(White white) {
        White result = whiteService.selectByPrimaryKey(white.getPhone());
        if (Objects.nonNull(result)) {
            return ResultUtils.error("手机号已存在");
        }
        white.setCreateTime(new Date());
        whiteService.insert(white);
        return ResultUtils.success();
    }

    @PostMapping("delete")
    @ApiOperation(value = "移除白名单")
    public ResultVO delete(String[] phones) {
        whiteService.batchDelete(phones);
        return ResultUtils.success();
    }

    @GetMapping("list")
    @ApiOperation(value = "查询白名单列表")
    @ApiImplicitParam(name = "phone", value = "手机号")
    public PageResultVO<List<White>> list(PageDTO dto, String phone) {
        Example example = new Example(White.class);
        example.orderBy("createTime").desc();
        if (StringUtils.isNotBlank(phone)) {
            example.createCriteria().andLike("phone", "%" + phone + "%");
        }
        PageHelper.startPage(dto.getPageNo(), dto.getPageSize());
        List<White> list = whiteService.selectByExample(example);
        PageInfo<White> pageInfo = new PageInfo<>(list);
        return ResultUtils.page(pageInfo);
    }
}
